/*
 * Copyright (c) Thorben Linneweber and others
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using Jitter2.LinearMath;

using SoftFloat;

namespace Jitter2.Collision.Shapes
{
	
	/// <summary>
	/// Wraps any shape and allows to orientate and translate it.
	/// </summary>
	public class TransformedShape : RigidBodyShape
	{
	    private enum TransformationType
	    {
	        Identity,
	        Rotation,
	        General
	    }
	
	    private NVector3 translation;
	    private JMatrix transformation;
	    private TransformationType type;
	
	    /// <summary>
	    /// Constructs a transformed shape through an affine transformation define by
	    /// a linear map and a translation. 
	    /// </summary>
	    /// <param name="shape">The original shape which should be transformed.</param>
	    /// <param name="translation">Shape is translated by this vector.</param>
	    /// <param name="transform">A linear map (may include sheer and scale) of the transformation.</param>
	    public TransformedShape(RigidBodyShape shape, in NVector3 translation, in JMatrix transform)
	    {
	        OriginalShape = shape;
	        this.translation = translation;
	        transformation = transform;
	
	        AnalyzeTransformation();
	        UpdateWorldBoundingBox(sfloat.Zero);
	    }
	
	    public TransformedShape(RigidBodyShape shape, NVector3 translation) :
	        this(shape, translation, JMatrix.Identity)
	    {
	    }
	
	    public RigidBodyShape OriginalShape { get; }
	
	    public NVector3 Translation
	    {
	        get => translation;
	        set
	        {
	            translation = value;
	            UpdateWorldBoundingBox(sfloat.Zero);
	        }
	    }
	
	    private void AnalyzeTransformation()
	    {
	        if (MathHelper.IsRotationMatrix(transformation, 1e-06f))
	        {
	            type = MathHelper.UnsafeIsZero(transformation - JMatrix.Identity, 1e-6f) ? TransformationType.Identity : TransformationType.Rotation;
	        }
	        else
	        {
	            type = TransformationType.General;
	        }
	    }
	
	    public JMatrix Transformation
	    {
	        get => transformation;
	        set
	        {
	            transformation = value;
	            AnalyzeTransformation();
	            UpdateWorldBoundingBox(sfloat.Zero);
	        }
	    }
	
	    public override void SupportMap(in NVector3 direction, out NVector3 result)
	    {
	        if (type == TransformationType.Identity)
	        {
	            OriginalShape.SupportMap(direction, out result);
	            result += translation;
	        }
	        else
	        {
	            NVector3.TransposedTransform(direction, transformation, out NVector3 dir);
	            OriginalShape.SupportMap(dir, out NVector3 sm);
	            NVector3.Transform(sm, transformation, out result);
	            result += translation;
	        }
	    
	        result += centerOffset;// 应用中心偏移
		}
	
	    public override void CalculateBoundingBox(in NQuaternion orientation, in NVector3 position, out JBBox box)
	    {
	        if (type == TransformationType.General)
	        {
	            // just get the bounding box from the support map
	            base.CalculateBoundingBox(orientation, position, out box);
	        }
	        else
	        {
	            NQuaternion quat = NQuaternion.CreateFromMatrix(transformation);
	            OriginalShape.CalculateBoundingBox(orientation * quat,
	                NVector3.Transform(translation, orientation) + position, out box);
	        }
	    
	        // 考虑位置和中心偏移
	        box.Min += centerOffset;
	        box.Max += centerOffset;
		}
	
	    public override void GetCenter(out NVector3 point)
	    {
	        OriginalShape.GetCenter(out point);
	        point = NVector3.Transform(point, transformation) + translation;
	    }
	
	    public override void CalculateMassInertia(out JMatrix inertia, out NVector3 com, out sfloat mass)
	    {
	        OriginalShape.CalculateMassInertia(out JMatrix oinertia, out NVector3 ocom, out mass);
	
	        com = NVector3.Transform(ocom, transformation) + translation;
	        inertia = transformation * JMatrix.Multiply(oinertia, JMatrix.Transpose(transformation));
	        JMatrix pat = mass * (JMatrix.Identity * translation.LengthSquared() - NVector3.Outer(translation, translation));
	        inertia += pat;
	    }
	}
}
